import requests
import time
import random
import json
import smtplib
from email.mime.text import MIMEText


num_list=[]
time_local = time.localtime(time.time())
date_time = time.strftime("%Y-%m-%d", time_local)
# print(date_time)
temp="36."+str(random.randint(2,6))
# print(temp)

post_url='https://stuhealth.jnu.edu.cn/api/write/main'
headers={
    "Content-Type": "application/json",
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36"
}

def send_email(email,res):
    msg_from = 'chenguiying5@163.com'  # 发送方邮箱
    passwd = 'ITQGNUYTXTVOZXPU'  # 填入发送方邮箱的授权码
    msg_to = email  # 收件人邮箱
    subject = "打卡结果提醒"  # 主题
    content = res  # 正文
    msg = MIMEText(content)
    msg['Subject'] = subject
    msg['From'] = msg_from
    msg['To'] = msg_to
    s = smtplib.SMTP_SSL("smtp.163.com", 465)  # 邮件服务器及端口号
    s.login(msg_from, passwd)
    s.sendmail(msg_from, msg_to, msg.as_string())
    print("发送成功")


def po(email,str_data):
    data_dict=json.loads(str_data)
    data_dict["mainTable"]["declareTime"]=date_time
    data_dict["mainTable"]["temperature"]=temp
    data=json.dumps(data_dict)
    response = requests.post(url=post_url, headers=headers, data=data)
    res=response.content.decode()
    print(res)
    send_email(email,res)

if __name__ == '__main__':
    f=open("num.txt","r")
    lines=f.readlines()
    f.close()
    for line in lines:
        line=line.strip("\n")
        num_list.append(line)


    for num in num_list:
        try:
            f=open(num+".txt","r")
            infors=f.readlines()
            f.close()
            for infor in infors:
                infor=infor.strip("\n")
            po(infors[0],infors[1])
        except:
            f=open("errorLog.txt","a")
            f.write(num)
            f.close()
            send_email("chengygy@foxmail.com",num+"  打卡失败提醒，请及时检查错误原因")
            continue

